package com.byd.dms.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.byd.dms.json2.Animal;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class JSON2Demo {
    
    /**
     * 默认序列化
     */
    @Test
    public void toJSONString() {
        Animal animal = new Animal();
        animal.setName("sam");
        animal.setSex(1);
        animal.setWeight(100);
        
        System.out.println(JSON.toJSONString(animal));
    }
    
    /**
     * 序列化时启用SerializerFeature.BeanToArray.<br>
     * 不序列化key，而是将value作为数组字符串输出，输出的json字符串更小，也节省了空间.<br>
     * 官方测试数据表示，启用后性能更好.
     */
    @Test
    public void toJSONStringWithBeanToArray() {
        Animal animal = new Animal();
        animal.setName("sam");
        animal.setWeight(100);
        animal.setSex(1);
        
        String str = JSON.toJSONString(animal, SerializerFeature.BeanToArray);
        System.out.println(str);
    }
    
    /**
     * 反序列化时启用Feature.SupportArrayToBean.<br>
     * 支持将json数组反序列化为JavaBean.
     */
    @Test
    public void parseObjectWithBeanToArray() {
        String jsonString = "[\"sam\",122,13]";
        
        Animal animal = JSON.parseObject(jsonString, Animal.class, Feature.SupportArrayToBean);
        
        Map<String, Object> map = new HashMap<>();
        map.put("name", "刘阿勇");
        map.put("age", 12);
        System.out.println(JSON.toJSONString(map));
        System.out.println(JSON.toJSONString(map, SerializerFeature.BeanToArray));
        
        System.out.println(JSON.toJSONString(animal));
    }
}
